package com.word.template.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Slf4j
public class PdfToImageConverter {

    public static byte[] pdfToOneImg(byte[] pdfByte){
        try {
            PDDocument document = PDDocument.load(pdfByte);
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            RenderedImage image = pdfRenderer.renderImageWithDPI(0, 300, ImageType.RGB);
            ImageIO.write(image, "PNG", outputStream);
            document.close();
            log.info("PDF pages converted to images successfully.");
            return outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pdfByte;
    }

//    public static void main(String[] args) throws Exception {
//        String pdfFilePath = "D:\\ruoyi\\111.pdf"; // 请替换为您的PDF文件路径
//        File file = new File(pdfFilePath);
//        FileInputStream fileInputStream = new FileInputStream(file);
//        byte[] bytes = new byte[(int) file.length()];
//        // 将文件内容读入 byte 数组
//        fileInputStream.read(bytes);
//        fileInputStream.close();
//        byte[] bytes1 = pdfToOneImg(bytes);
//
//        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes1);
//        BufferedImage image = ImageIO.read(byteArrayInputStream);
//        byteArrayInputStream.close();
//        ImageIO.write(image, "png", new File("D:\\ruoyi\\1232222456.png"));
//
//    }

}
